<?php

/**
 * Search
 */
require_once YSP_ROOT_BASE . '/extends/xunsearch/php/lib/XS.php';

class ExtendsYspSearch {

    /**
     * $_config array
     *
     * @var string $_file xunSearch configuration ini file path
     * @var string charset DefaultCharset
     */
    private $_config;

    /**
     * XS object
     * @var type object
     */
    private $_search = NULL;
    private $_tokenizer = NULL;

    public function __construct($config = array()) {
        $this->_config = $config + array('file' => '15ketang_tags', 'charset' => 'UTF-8');

        $this->init();
    }

    /**
     * instance search at XS
     * @return object
     */
    private function init() {
        if (NULL === $this->_search) {
            $this->_search = new XS($this->_config['file']);
            $this->_search->setDefaultCharset($this->_config['charset']);
        }

        return $this;
    }

    /**
     * return tokenizer
     */
    public function getTokenizer() {
        if (NULL === $this->_tokenizer) {
            $this->_tokenizer = new XSTokenizerScws;
        }

        return $this->_tokenizer;
    }

    /**
     * return xun search object
     */
    public function getSearch() {
        return $this->_search;
    }

    /**
     * get search result by key
     * @param string $tag search by key
     * @return mixed
     */
    public function get($tag) {

        $tag = 'tags:' . ' ' . $tag;

        return $this->_search->search->search($tag);
    }

    /**
     * update to search db
     * @param string $id search id eg. 10001
     * @param string $title
     * @param string $content
     * @param string $tags tag eg. tag1, tag2...
     * @param timestamp $time date
     * @param string $send_id send object id
     * @return boolean TRUE
     * @throws Exception
     */
    public function set($id, $title, $content, $tags = NULL, $time = NULL) {
        try {
            $data = array(
                'id' => $id,
                'tags' => $tags,
                'title' => strip_tags($title),
                'desc' => strip_tags($content),
                'postTime' => (NULL === $time) ? time() : $time
            );

            $doc = new XSDocument;
            $doc->setFields($data);

            $this->_search->getIndex()->update($doc);
            return TRUE;
        } catch (XSException $exc) {
            throw new Exception($exc->getMessage(), $exc->getCode());
        }
    }

    /*
     * delete data for search
     * @param array $ids
     * @param string $type
     * @return bool
     * @throws Exception
     */

    public function delete($ids, $type = NULL) {
        try {
            $this->_search->index->del($ids);
            return TRUE;
        } catch (XSException $exc) {
            throw new Exception($exc->getMessage(), $exc->getCode());
        }
    }

}
